package com.huawei.cloud.phone.management.domain.connection.status;

import com.huawei.cloud.phone.management.common.BeanFactory;
import com.huawei.cloud.phone.management.common.exception.DisconnectException;
import com.huawei.cloud.phone.management.common.exception.InvalidConnectionStatusException;
import com.huawei.cloud.phone.management.domain.connection.Connection;
import com.huawei.cloud.phone.management.domain.connection.ConnectionGateway;

import java.util.Optional;

public final class ConnectionStateFactory {
    private ConnectionStateFactory() {
    }

    /**
     * 获取连接状态
     *
     * @param phoneId 手机ID
     * @return 连接状态
     */
    public static ConnectionState getState(String phoneId) {
        return getOptionalState(phoneId).orElseThrow(() -> new DisconnectException(phoneId));
    }

    /**
     * 获取连接状态
     *
     * @param phoneId 手机ID
     * @return 连接状态
     */
    public static Optional<ConnectionState> getOptionalState(String phoneId) {
        ConnectionGateway gateway = BeanFactory.getBean(ConnectionGateway.class);
        Optional<Connection> connection = gateway.getConnectionByPhoneId(phoneId);
        return connection.map(ConnectionStateFactory::revertState);
    }

    private static ConnectionState revertState(Connection connection) {
        switch (connection.getStatus()) {
            case CONNECTED:
                return new ConnectedState(connection);
            case IDLE:
                return new IdleState(connection);
            case UNKNOWN:
                return new UnknownState(connection);
            default:
                throw new InvalidConnectionStatusException(connection.getPhoneId(), connection.getStatus().name());
        }
    }
}
